import logging
import sys
from typing import Optional

class MultilineFormatter(logging.Formatter):
    """带统一前缀的多行日志格式化器"""
    def format(self, record):
        prefix = f"[{self.formatTime(record, self.datefmt)}][{record.levelname}]|"
        message = super().format(record)
        return '\n'.join(f"{prefix} {line}" for line in message.split('\n'))

class GlobalLogger:
    _instance = None 
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self.logger = logging.getLogger("GlobalLogger")
            self.logger.setLevel(logging.DEBUG)
            self._initialized = True
    
    def init(self,
             log_file: Optional[str] = None,
             level: int = logging.INFO,
             enable_console: bool = True,
             fmt: str = "%(message)s",
             datefmt: str = "%Y-%m-%d %H:%M:%S"):
        """初始化全局日志配置"""
        # 清除已有处理器
        for handler in self.logger.handlers[:]:
            self.logger.removeHandler(handler)
        
        # 创建格式化器
        formatter = MultilineFormatter(fmt, datefmt)
        
        # 文件处理器
        if log_file:
            file_handler = logging.FileHandler(log_file, encoding="utf-8")
            file_handler.setFormatter(formatter)
            self.logger.addHandler(file_handler)
        
        # 控制台处理器
        if enable_console:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setFormatter(formatter)
            self.logger.addHandler(console_handler)
        
        # 设置日志级别
        self.logger.setLevel(level)
    
    def __getattr__(self, name):
        """代理logging.Logger的方法"""
        return getattr(self.logger, name)

# 全局访问点
GLOBAL_LOGGER = GlobalLogger()

# 快捷初始化函数
def init_global_logger(log_file: Optional[str] = None,
                      level: int = logging.INFO,
                      enable_console: bool = True):
    GLOBAL_LOGGER.init(log_file=log_file,
                      level=level,
                      enable_console=enable_console)